package com.mes.web.controller.cb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mes.entity.cb.MaMove;
import com.mes.entity.cb.MaReturn;
import com.mes.entity.cb.Materiel;
import com.mes.entity.jy.Tempma;
import com.mes.entity.lz.BOM;
import com.mes.entity.tdd.ProcurementChuku;
import com.mes.entity.tdd.ProcurementChukuMateriel;
import com.mes.service.cb.MaMoveService;
import com.mes.service.cb.MaReturnService;
import com.mes.service.cb.MaStockService;
import com.mes.service.cb.WarehouRedService;
import com.mes.service.jy.TempmaService;
import com.mes.service.jy.TempproductServise;
import com.mes.utils.StringUtil;

/**
 * @ClassName: PhoneController
 * @Description: 给pda写后台代码
 * @Author cb
 * @Date 2018年4月11日14:49:41
 * @version 1.0
 */
@Controller
@RequestMapping("/phone")
public class PhoneController {

    @Resource
    private WarehouRedService warehouRedService;

    @Resource
    private MaReturnService maReturnService;

    @Resource
    private MaMoveService maMoveService;

    @Resource
    private TempmaService tempmaService;

    @Resource
    private MaStockService maStockService;
    
    @Resource
	private TempproductServise tempproductServise;

    /**
     * 领料移库是根据条码查询货物
     * @param productLine
     */
    @RequestMapping("/storck_ByCode")
    @ResponseBody
    public Map<String, Object> storck_ByCode(String productLine) {
       Materiel materiel =  warehouRedService.storck_ByCode(productLine);

       Map<String,Object> amp = new HashMap<>();
       
       if(materiel != null) {
    	   amp.put("code","200");
           amp.put("message","");
           amp.put("results",materiel);
       }else {
    	   amp.put("code","500");
           amp.put("message","没有条码");
           
       }
       return amp;
    }
    
    @RequestMapping("/storck_ByMaid")
    @ResponseBody
    public Map<String,Object> storck_ByMaid(String maid) {
    	List<String> codes = maStockService.storck_ByMaid(Long.parseLong(maid));
    	
    	Map<String,Object> amp = new HashMap<>();
        amp.put("code","200");
        amp.put("message","");
        amp.put("results",codes);
    	
    	return amp;
    }
    
    

    /**
     * 查询所有审核过的退货单
     * @return
     */
    @RequestMapping("/maReturn_listAll")
    @ResponseBody
    public Map<String, Object> maReturn_listAll() {
        List<ProcurementChuku> list = maReturnService.maReturn_listAll();
        Map<String,Object> amp = new HashMap<>();

        amp.put("code","200");
        amp.put("message","");
        amp.put("results",list);
        return amp;

    }

    /**
     * 根据id查询所有的退货的物料
     * @param returnBillId 退货单id
     * @return
     */
    @RequestMapping("/maReturnMa_selectByPcId")
    @ResponseBody
    public Map<String, Object> maReturnMa_selectByPcId(String returnBillId) {

        List<ProcurementChukuMateriel> list = maReturnService.maReturnMa_selectByPcId(returnBillId);

        Map<String,Object> amp = new HashMap<>();

        amp.put("code","200");
        amp.put("message","");
        amp.put("results",list);
        return amp;

    }

    /**
     * 退货操作
     * @param userId 操作人
     * @param returnBillId 退货单id
     * @param procurementChukuMaterielList 实体
     */
    @RequestMapping("/maReturnMa_insert")
    @ResponseBody
    public Map<String,Object> maReturnMa_insert(String userId,String returnBillId, String procurementChukuMaterielList) {

        List<ProcurementChukuMateriel> list = getListPersonByGson(procurementChukuMaterielList);


        List<MaReturn> maReturns = new  ArrayList<>();

        List<String> str = new ArrayList<String>();
        

        for (ProcurementChukuMateriel pm : list) {


            MaReturn maReturn = new MaReturn();
            //退货id
            maReturn.setRid(Long.parseLong(returnBillId));
            //条码
            maReturn.setRcode(pm.getPcmremark2());
            str.add(pm.getPcmremark2());
            //批号
            maReturn.setRpihao(pm.getPcmremark1());
            
            //是否条码
            maReturn.setRcancode("1");
            //物料id
            maReturn.setRamid(pm.getMaterielid().toString());
            //数量
            maReturn.setRnum(Long.parseLong(pm.getNumber()));
            //操作人
            maReturn.setRman(userId);
            
            maReturns.add(maReturn);
            
            maReturn = null;

        }

        //添加退货记录
        int effect =  maReturnService.maReturnMa_insert(maReturns);


        Map<String,Object> amp = new HashMap<>();



        if(effect > 0) {
        	
        	//减库存
			maStockService.maStock_deleteBy(str);
			
			//退货状态
			maStockService.update_tuihuoState(Long.parseLong(returnBillId));
			
            amp.put("code","200");
            amp.put("message","退货成功");

        }else {
            amp.put("code","500");
            amp.put("message","退货失败");
        }

        return amp;

    }


    /**
     * 解析jsonArray
     * @param ProcurementChukuMateriel
     */
    private List<ProcurementChukuMateriel> getListPersonByGson(String ProcurementChukuMateriel) {
        List<ProcurementChukuMateriel> list;
        Gson gson = new Gson();

        list = gson.fromJson(ProcurementChukuMateriel, new TypeToken<List<ProcurementChukuMateriel>>(){}.getType());

        return list;
    }

    /**
     * 领料添加
     * @param bomList BOM对象集合
     * @param userId 操作人
     * @param requisitionId 领料单id
     */
    @RequestMapping("/maMove_insert")
    @ResponseBody
    public Map<String,Object> maMove_insert(String bomList,String userId,String requisitionId) {

    	Integer diff = 0;
    	Integer diffStatic = 0;
    	
        if (StringUtil.isEmpty(bomList)) {
            return null;
        }

        List<BOM> boms = getListPersonByGson2(bomList);

        List<MaMove> list = new ArrayList<>();

        List<String> str = new ArrayList<>();

        for (BOM bom : boms) {
            Tempma tempma = new Tempma();
            MaMove maMove = new MaMove();
            String code =  bom.getRemark14();
            //领料id
            maMove.setLid(Long.parseLong(requisitionId));
            //条码
            maMove.setCode(code);
            tempma.setRemark1(code);
            str.add(code);
            //批号
            maMove.setMpihao(bom.getRemark15());
            tempma.setRemark(bom.getRemark15());
            //物料id
            maMove.setMaMid(bom.getRemark05());
            tempma.setPid(bom.getRemark05());
            //数量
            Integer snum = Integer.valueOf( bom.getLingliaoRequireCount());
            maMove.setCnum(snum+"");
            tempma.setRemark4(snum+"");

            
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            
            //是否扫码
            maMove.setScanCode("1");
            
            tempma.setDatatime(format.format(new Date()));

            //人员
            maMove.setMans(Long.parseLong(userId));

            int affact = tempmaService.createTempMa(tempma);

            list.add(maMove);

            //根据条码   查询  数量  在物料库
            Integer num =  tempproductServise.selectMaStokNumBycode(code);
            //用条码数量 - 应领料数量    做对比
            diff = num - snum ;
            bom.setRemark09(Long.parseLong(requisitionId)+"");
            bom.setRemark08(diff+"");
            //根据物料id和领料单修改领料单 单id中物料的应领料数量
            tempproductServise.updateNumByOrderAndMid(bom);
            
            if(diff < 0) {
            	diffStatic = -1;
            }
            
            maMove = null;
            tempma = null;
        }

        int total = maMoveService.maMove_insert(list);


        Map<String,Object> amp = new HashMap<>();

        if(total > 0) {

            maStockService.maStock_deleteBy(str);

            
            //如果，条码中的数量大于等于 应领料数量 时  再更改领料单状态
            if(diffStatic == 0) {
            	 //更改侯艳领料状态
                maMoveService.maStock_deleteByHy(Long.parseLong(requisitionId));
            }
            
            amp.put("code","200");
            amp.put("message","领料成功");

        }else {
            amp.put("code","500");
            amp.put("message","领料失败");
        }

        return amp;

    }

    /**
     * 解析jsonArray
     * @param BOM
     */
    private List<BOM> getListPersonByGson2(String BOM) {
        List<BOM> list;
        Gson gson = new Gson();

        list = gson.fromJson(BOM, new TypeToken<List<BOM>>(){}.getType());

        return list;
    }

}
